﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Metro.Core;

namespace Weather
{
    /// <summary>
    /// Interaction logic for WidgetControl.xaml
    /// </summary>
    public partial class WidgetControl : UserControl
    {
        private Options _options;

        public List<WeatherProvider> Providers;
        public WeatherProvider CurrentProvider;
        public WeatherReport WeatherReport;

        public WidgetControl()
        {
            InitializeComponent();
        }

        public void Load()
        {
            if (DateTime.Now.Hour >= 19 && DateTime.Now.Hour <= 4)
                Widget.Instance.SetBackground(Brushes.Black);

            var optionsItem = new MenuItem { Header = Widget.Instance.LocaleManager.GetString("Options") };
            optionsItem.Click += OptionsItemClick;

            var refreshItem = new MenuItem { Header = Widget.Instance.LocaleManager.GetString("Refresh") };
            refreshItem.Click += refreshItem_Click;

            Widget.Instance.AddMenuItem(optionsItem);
            Widget.Instance.AddMenuItem(refreshItem);

            WeatherReport = WeatherReport.Read(E.Path + "\\Weather\\Weather.data");
            UpdateWeatherData();
            GetWeatherProviders();

            _options = new Options();
        }

        private void GetWeatherProviders()
        {
            if (Directory.Exists(E.Path + "\\Weather\\WeatherProviders"))
            {
                Providers = new List<WeatherProvider>();
                var files = from x in Directory.GetFiles(E.Path + "\\Weather\\WeatherProviders")
                            where x.EndsWith(".dll")
                            select x;
                foreach (var f in files)
                {
                    var p = new WeatherProvider(f);
                    Providers.Add(p);
                    if (Widget.Instance.Sett.WeatherProvider == p.Name)
                    {
                        CurrentProvider = p;
                        p.Load();
                    }
                }
            }
        }

        void OptionsItemClick(object sender, RoutedEventArgs e)
        {
            if (_options.IsVisible)
            {
                _options.Activate();
                return;
            }
            _options = new Options();

            if (E.Locale == "he-IL" || E.Locale == "ar-SA")
            {
                _options.FlowDirection = FlowDirection.RightToLeft;
            }
            else
            {
                _options.FlowDirection = FlowDirection.LeftToRight;
            }

            _options.ShowDialog();
        }

        void refreshItem_Click(object sender, RoutedEventArgs e)
        {
            ThreadStart threadStarter = RefreshWeather;
            var thread = new Thread(threadStarter);
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }

        public void RefreshWeather()
        {
            try
            {
                GetWeatherReport();

                if (WeatherReport != null)
                    this.Dispatcher.Invoke((Action)UpdateWeatherData, null);
            }
            catch (Exception ex)
            {
                //this.Dispatcher.Invoke((Action)RefreshWeatherFail, null);
                Metro.Core.Logger.Log(ex.ToString());
            }
        }

        private void GetWeatherReport()
        {
            WeatherReport temp;
            if (Widget.Instance.Sett.LocationCode != string.Empty)
            {
                temp = CurrentProvider.GetWeatherReport(E.Locale, Widget.Instance.Sett.LocationCode, Widget.Instance.Sett.DegreeType);
            }
            else
            {
                temp = CurrentProvider.GetWeatherReport(E.Locale, string.Empty, Widget.Instance.Sett.DegreeType);
            }

            if (temp != null)
                WeatherReport = temp;
        }

        private void UpdateWeatherData()
        {
            if (!string.IsNullOrEmpty(WeatherReport.Location))
            {
                if (WeatherReport.Location.Contains(","))
                    WeatherReport.Location = WeatherReport.Location.Substring(0, WeatherReport.Location.IndexOf(","));

                //City.Text = weatherReport.Location;

                WeatherIcon.Source = new BitmapImage(new Uri(string.Format("/Weather;component/Resources/weather_{0}.png", WeatherReport.NowSkyCode), UriKind.Relative));

                //SetWeatherState(weatherReport.NowSkyCode);
            }

            NowTemp.Text = WeatherReport.NowTemp + "°";

            HLTemp.Text = WeatherReport.High + "° / " + WeatherReport.Low + "°";

            /*if (!string.IsNullOrEmpty(WeatherReport.NowSky))
                Weather.Text = weatherReport.NowSky;*/
        }

        public void Unload()
        {
            if (WeatherReport != null)
            {
                WeatherReport.Write(E.Path + "\\Weather\\Weather.data");
            }
        }
    }
}
